import pymysql
from dbutils.pooled_db import PooledDB
import os
from configparser import ConfigParser
from dataop import config

jdy_api_conf = config.Config("config", "project_info.conf").get_config()



# [mysql_155]
# host= 43.153.158.155
# hostName= ruyibi.online
# port= 3306
# schemaName= test
# username= app_admin
# passwd= Qwer123$
# charset= utf8

class datasource:
    def __init__(self, source_name):
        self.source_name = source_name

    def getdatasource(self):
        host = jdy_api_conf.get(self.source_name, "host")
        user = jdy_api_conf.get(self.source_name, "username")
        passwd = jdy_api_conf.get(self.source_name, "passwd")
        db = jdy_api_conf.get(self.source_name, "schemaName")
        port = int(jdy_api_conf.get(self.source_name, "port"))
        charset = jdy_api_conf.get(self.source_name, "charset")
        # print(host , user,passwd, port, charset)

        pool = PooledDB(pymysql, 5, host=host, user=user, passwd=passwd, db=db, port=port, charset=charset)
        return pool

    def execCustomSql(self, sql):
        pool = self.getdatasource()
        conn = pool.connection()
        cursor = conn.cursor()
        # print(sql)
        try:
            cursor.execute(sql)
            conn.commit()
        except Exception as e:
            print(e)
            conn.rollback()
        cursor.close()
        conn.close()
        return sql
